package cn.vihub.service.impl;

import cn.vihub.handler.MyRuntimeException;
import cn.vihub.service.TokenService;
import cn.vihub.vo.TokenVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author: 秋晚
 * @Date: 2025/7/20 18:12
 * @Description:
 **/
@Service

public class TokenServiceImpl implements TokenService {


    /**
     * @author: 秋晚
     * @description:登录获取token接口
     * @params: [java.lang.Integer, java.lang.String]
     * @return: cn.vihub.vo.TokenVo
     * @date: 2025/7/21 15:21
     */
    @Override
    public TokenVo createAccessToken(Integer id, String username) {
        //设置失效时间
        Long expTime=System.currentTimeMillis() + 7200000;
        //生成登录token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "128903djsjhduihas167645")
                .setId(id + "")
                .claim("userId", id)
                .claim("username", username)
                .compact();

        //设置长期token过期时间
        Long refreshExpTime=System.currentTimeMillis()+(86400000*7);
        //生成refreshToken
        String refreshToken = Jwts.builder().signWith(SignatureAlgorithm.HS256, "128903djsjhduihas167645")
                .setExpiration(new Date(refreshExpTime))
                .setId(id + "")
                .claim("userId", id)
                .claim("username", username)
                .claim("status", "refresh")
                .compact();


        //创建对象
        TokenVo tokenVo = new TokenVo();
        tokenVo.setAccessToken(token);
        tokenVo.setAccessTokenTime(expTime);
        tokenVo.setRefreshToken(refreshToken);
        tokenVo.setRefreshTokenTime(refreshExpTime);
        return tokenVo;
    }

    @Override
    public TokenVo getRefreshToken(String refreshToken) {

        try {
            //解析token
            Claims body = Jwts.parser().setSigningKey("128903djsjhduihas167645")
                    .parseClaimsJws(refreshToken)
                    .getBody();

            //获取过期时间
            Date expiration = body.getExpiration();
            //获取userId和username
            Integer userId = body.get("userId", Integer.class);
            String username = body.get("username", String.class);
            //调用生成token重新刷新短期token
            TokenVo tokenVo = createAccessToken(userId, username);

//            refreshToken和过期时间还用原来的
            tokenVo.setRefreshToken(refreshToken);
            tokenVo.setRefreshTokenTime(expiration.getTime());

            return tokenVo;
        }catch (Exception e){
            throw new MyRuntimeException("token失效或者非法!");
        }

    }
}
